<template>
  <el-dialog
    :title="title"
    v-model="dialogVisible"
    width="1100px"
    @close="handleClose"
  >
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="queryParams">
        <el-form-item label="分类名称">
          <el-input v-model="queryParams.name" placeholder="请输入分类名称" clearable />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" style="width: 120px" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="operation-container">
      <el-button type="primary" @click="handleAdd">新增分类</el-button>
    </div>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="categoryList">
      <el-table-column label="分类名称" prop="name" />
      <el-table-column label="排序" prop="sort" width="100" align="center" />
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="180" />
      <el-table-column label="操作" width="150" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.current"
        v-model:page-size="queryParams.size"
        :total="total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑弹窗 -->
    <el-dialog
      :title="form.id ? '编辑分类' : '新增分类'"
      v-model="formDialog.visible"
      width="500px"
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="99" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="formDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, defineProps, defineEmits, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCategoryList, addCategory, updateCategory, deleteCategory } from '@/api/articleCategory'

const props = defineProps({
  title: {
    type: String,
    default: '分类管理'
  },
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'refresh'])

// 控制弹窗显示
const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
})

// 查询参数
const queryParams = reactive({
  current: 1,
  size: 10,
  name: '',
  status: undefined
})

// 表格数据
const loading = ref(false)
const categoryList = ref([])
const total = ref(0)

// 获取列表数据
const getList = async () => {
  try {
    loading.value = true
    const res = await getCategoryList(queryParams)
    categoryList.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    console.error('获取分类列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询操作
const handleQuery = () => {
  queryParams.current = 1
  getList()
}

// 重置查询
const resetQuery = () => {
  queryParams.name = ''
  queryParams.status = undefined
  handleQuery()
}

// 表单数据
const formRef = ref()
const formDialog = reactive({
  visible: false
})
const form = reactive({
  id: undefined,
  name: '',
  sort: 0,
  status: 1
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ]
}

// 新增分类
const handleAdd = () => {
  form.id = undefined
  form.name = ''
  form.sort = 0
  form.status = 1
  formDialog.visible = true
}

// 编辑分类
const handleEdit = (row) => {
  Object.assign(form, row)
  formDialog.visible = true
}

// 删除分类
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该分类吗?', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteCategory(row.id)
      ElMessage.success('删除成功')
      getList()
      emit('refresh')
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id) {
          await updateCategory(form)
          ElMessage.success('更新成功')
        } else {
          await addCategory(form)
          ElMessage.success('新增成功')
        }
        formDialog.visible = false
        getList()
        emit('refresh')
      } catch (error) {
        console.error('保存失败:', error)
      }
    }
  })
}

// 分页操作
const handleSizeChange = (val) => {
  queryParams.size = val
  getList()
}

const handleCurrentChange = (val) => {
  queryParams.current = val
  getList()
}

// 弹窗关闭
const handleClose = () => {
  emit('update:visible', false)
}

// 初始化
onMounted(() => {
  if (props.visible) {
    getList()
  }
})

// 监听弹窗显示变化
watch(() => props.visible, (val) => {
  if (val) {
    getList()
  }
})
</script>

<style lang="scss" scoped>
.search-container {
  margin-bottom: 20px;
}

.operation-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style>
